<template>
<div class="chat-container">
    <!-- 顶部导航栏 -->
    <van-nav-bar :title="chatInfo.name" left-arrow @click-left="onBack" @click-right="showChatInfo">
        <template #right>
            <div class="nav-right-actions">
                <van-icon name="search" size="20" @click.stop="viewChatDetail" />
                <van-icon name="ellipsis" size="20" />
            </div>
        </template>
    </van-nav-bar>

    <!-- 消息列表 -->
    <div class="chat-messages" ref="messageList">
        <!-- 日期分割线 -->
        <div class="date-divider" v-for="(date, index) in messageDates" :key="'date-' + index">
            <span>{{ date }}</span>
        </div>

        <!-- 消息气泡 -->
        <div v-for="(message, index) in messages" :key="index"
            :class="['message-item', message.isSelf ? 'message-self' : 'message-other']">
            <!-- 头像 -->
            <div class="message-avatar" v-if="!message.isSelf" @click="viewUserProfile(message.userId)">
                <img :src="message.avatar" :alt="message.sender">
            </div>

            <!-- 消息内容 -->
            <div class="message-content">
                <!-- 发送者名称 (仅在群聊中显示) -->
                <div class="message-sender" v-if="!message.isSelf && isGroupChat">
                    {{ message.sender }}
                </div>

                <!-- 文本消息 -->
                <div v-if="message.type === 'text'" class="message-bubble" :class="{ 'self-bubble': message.isSelf }">
                    <span v-html="formatMessage(message.content)"></span>
                </div>

                <!-- 图片消息 -->
                <div v-else-if="message.type === 'image'" class="message-image" @click="previewImage(message.content)">
                    <img :src="message.content" alt="图片">
                </div>

                <!-- 语音消息 -->
                <div v-else-if="message.type === 'voice'" class="message-voice"
                    :class="{ 'self-bubble': message.isSelf }" @click="playVoice(message.content)">
                    <van-icon name="volume" />
                    <span>{{ message.duration }}''</span>
                </div>

                <!-- 视频消息 -->
                <div v-else-if="message.type === 'video'" class="message-video" @click="playVideo(message.content)">
                    <div class="video-thumbnail">
                        <img :src="message.thumbnail" alt="视频缩略图">
                        <div class="play-icon">
                            <van-icon name="play-circle-o" size="40" />
                        </div>
                    </div>
                </div>

                <!-- 笔记卡片 -->
                <div v-else-if="message.type === 'note'" class="message-note" @click="viewNote(message.noteId)">
                    <div class="note-card">
                        <div class="note-image">
                            <img :src="message.thumbnail" alt="笔记缩略图">
                        </div>
                        <div class="note-info">
                            <div class="note-title">{{ message.title }}</div>
                            <div class="note-desc">{{ message.description }}</div>
                        </div>
                    </div>
                </div>

                <!-- 时间显示 -->
                <div class="message-time" v-if="showMessageTime(index)">
                    {{ formatTime(message.time) }}
                </div>
            </div>

            <!-- 头像 (自己发送的消息) -->
            <div class="message-avatar" v-if="message.isSelf">
                <img :src="message.avatar" :alt="message.sender">
            </div>
        </div>

        <!-- 加载更多 -->
        <div class="load-more" v-if="hasMoreMessages" @click="loadMoreMessages">
            <van-loading size="16px" v-if="isLoading">加载中...</van-loading>
            <span v-else>加载更多消息</span>
        </div>
    </div>

    <!-- 输入区域 -->
    <div class="chat-input-area">
        <div class="input-toolbar">
            <van-icon name="voice-o" size="24" @click="toggleVoiceInput" />
            <van-field v-model="inputMessage" placeholder="发送消息..." :type="isVoiceInput ? 'hidden' : 'text'"
                @keypress.enter.native.prevent="sendTextMessage" />
            <div class="voice-button" v-if="isVoiceInput" @touchstart="startRecording" @touchend="stopRecording">
                按住说话
            </div>
            <van-icon name="smile-o" size="24" @click="showEmojiPanel = !showEmojiPanel" />
            <van-icon name="add-o" size="24" @click="showMorePanel = !showMorePanel" />
        </div>

        <!-- 表情面板 -->
        <div class="emoji-panel" v-show="showEmojiPanel">
            <div class="emoji-grid">
                <div v-for="(emoji, index) in emojiList" :key="index" class="emoji-item" @click="insertEmoji(emoji)">
                    {{ emoji }}
                </div>
            </div>
        </div>

        <!-- 更多功能面板 -->
        <div class="more-panel" v-show="showMorePanel">
            <div class="more-grid">
                <div class="more-item" @click="chooseImage">
                    <div class="more-icon">
                        <van-icon name="photo-o" size="24" />
                    </div>
                    <div class="more-text">相册</div>
                </div>
                <div class="more-item" @click="takePhoto">
                    <div class="more-icon">
                        <van-icon name="photograph" size="24" />
                    </div>
                    <div class="more-text">拍摄</div>
                </div>
                <div class="more-item" @click="chooseNote">
                    <div class="more-icon">
                        <van-icon name="notes-o" size="24" />
                    </div>
                    <div class="more-text">笔记</div>
                </div>
                <div class="more-item" @click="shareLocation">
                    <div class="more-icon">
                        <van-icon name="location-o" size="24" />
                    </div>
                    <div class="more-text">位置</div>
                </div>
            </div>
        </div>
    </div>

    <!-- 群聊信息弹出层 -->
    <van-popup v-model="showGroupInfo" position="right" :style="{ width: '80%', height: '100%' }">
        <group-info v-if="isGroupChat" :group-id="chatId" @close="showGroupInfo = false" />
        <user-info v-else :user-id="chatId" @close="showGroupInfo = false" />
    </van-popup>
</div>
</template>

<script>
import { defineComponent } from 'vue'
import { mapGetters } from 'vuex'
import { Toast, Dialog } from 'vant'
import dayjs from 'dayjs'
import { websocketApi } from '@/api/websocket'

export default defineComponent({
    name: 'ChatView',
    components: {
        GroupInfo: () => import('@/components/chat/GroupInfo.vue'),
        UserInfo: () => import('@/components/chat/UserInfo.vue')
    },
    data() {
        return {
            chatId: '',
            chatInfo: {
                name: '',
                avatar: '',
                members: []
            },
            isGroupChat: false,
            messages: [],
            messageDates: [],
            inputMessage: '',
            isVoiceInput: false,
            showEmojiPanel: false,
            showMorePanel: false,
            showGroupInfo: false,
            hasMoreMessages: true,
            isLoading: false,
            page: 1,
            emojiList: [
                '😊', '😂', '😍', '🤔', '😒', '👍', '👏', '🎉',
                '🌹', '🍓', '🍕', '🏠', '🚗', '⚽', '🏆', '🎵'
            ]
        }
    },
    computed: {
        ...mapGetters([
            'user'
        ]),
        currentUser() {
            return this.user || { id: 0, nickname: '未登录', avatar: 'https://i.pravatar.cc/100?img=10' }
        }
    },
    created() {
        this.chatId = this.$route.params.id
        this.isGroupChat = this.chatId.startsWith('g')
        this.fetchChatInfo()
        this.fetchMessages()
        // 初始化WebSocket
        this.initWebSocket()
    },

    beforeDestroy() {
        // 移除WebSocket消息处理回调
        websocketApi.offMessage(this.handleWebSocketMessage)
        // 清除当前聊天会话
        this.$store.commit('setCurrentChatSession', null)
    },
    mounted() {
        this.scrollToBottom()
    },
    updated() {
        this.scrollToBottom()
    },
    methods: {
        // 初始化WebSocket连接
        initWebSocket() {
            // 注册消息处理回调
            websocketApi.onMessage(this.handleWebSocketMessage)

            // 如果未连接，则连接WebSocket
            if (!websocketApi.isConnected()) {
                websocketApi.connect()
            }

            // 设置当前聊天会话
            this.$store.commit('setCurrentChatSession', this.chatInfo.userId)
        },

        // 获取聊天信息
        fetchChatInfo() {
            // 模拟API请求
            setTimeout(() => {
                if (this.isGroupChat) {
                    this.chatInfo = {
                        name: '【群聊】没想好名字',
                        avatar: '',
                        members: [
                            { id: 1, name: 'momo', avatar: 'https://i.pravatar.cc/100?img=1' },
                            { id: 2, name: '悟空', avatar: 'https://i.pravatar.cc/100?img=2' },
                            { id: 3, name: '用户3', avatar: 'https://i.pravatar.cc/100?img=3' },
                            { id: 4, name: '用户4', avatar: 'https://i.pravatar.cc/100?img=4' }
                        ]
                    }
                } else {
                    this.chatInfo = {
                        name: 'momo',
                        avatar: 'https://i.pravatar.cc/100?img=4',
                        members: []
                    }
                }
            }, 100)
        },

        // 获取聊天消息
        fetchMessages() {
            this.isLoading = true
            // 模拟API请求
            setTimeout(() => {
                const newMessages = this.generateMessages(this.page)
                this.messages = [...newMessages, ...this.messages]
                this.updateMessageDates()
                this.isLoading = false
                this.hasMoreMessages = this.page < 3
                this.page++
            }, 500)
        },

        // 生成模拟消息
        generateMessages(page) {
            const baseTime = new Date()
            baseTime.setHours(baseTime.getHours() - (page - 1) * 6)

            const messages = []
            const count = 10

            for (let i = 0; i < count; i++) {
                const time = new Date(baseTime)
                time.setMinutes(time.getMinutes() - i * 5)

                const isSelf = Math.random() > 0.5
                const messageTypes = ['text', 'image', 'voice', 'note']
                const type = messageTypes[Math.floor(Math.random() * (i === 0 ? 1 : 4))]

                let content = '', duration, thumbnail, title, description, noteId

                switch (type) {
                    case 'text':
                        content = this.getRandomText()
                        break
                    case 'image':
                        content = `https://picsum.photos/300/400?random=${Math.floor(Math.random() * 1000)}`
                        break
                    case 'voice':
                        content = 'voice_message.mp3'
                        duration = Math.floor(Math.random() * 60) + 1
                        break
                    case 'note':
                        noteId = Math.floor(Math.random() * 1000)
                        thumbnail = `https://picsum.photos/300/400?random=${Math.floor(Math.random() * 1000)}`
                        title = '我的生活记录'
                        description = '分享我的日常生活点滴...'
                        break
                }

                messages.push({
                    id: Date.now() + i,
                    type,
                    content,
                    time: time.getTime(),
                    isSelf,
                    sender: isSelf ? '我' : this.getRandomSender(),
                    userId: isSelf ? 'self' : Math.floor(Math.random() * 10) + 1,
                    avatar: isSelf
                        ? 'https://i.pravatar.cc/100?img=10'
                        : `https://i.pravatar.cc/100?img=${Math.floor(Math.random() * 9) + 1}`,
                    duration,
                    thumbnail,
                    title,
                    description,
                    noteId
                })
            }

            return messages
        },

        // 获取随机文本
        getRandomText() {
            const texts = [
                '你好，最近怎么样？',
                '我刚刚看到一个很有趣的视频，待会发给你',
                '周末有什么计划吗？',
                '这个笔记不错，推荐你看看',
                '今天天气真好，出去走走吧',
                '你看到最新的活动了吗？',
                '我们下周一起去看电影吧',
                '这家店的菜真的很好吃，下次带你去',
                '最近有什么好看的电视剧推荐吗？',
                '我刚买了一件新衣服，你觉得怎么样？'
            ]
            return texts[Math.floor(Math.random() * texts.length)]
        },

        // 获取随机发送者
        getRandomSender() {
            if (!this.isGroupChat) return this.chatInfo.name

            const members = this.chatInfo.members
            return members[Math.floor(Math.random() * members.length)].name
        },

        // 处理WebSocket消息
        handleWebSocketMessage(message) {
            // 只处理聊天类型消息
            if (message.type !== 'chat') {
                return
            }

            // 检查消息是否属于当前聊天
            const isCurrentChat = message.isSelf ?
                message.to === this.chatInfo.userId :
                message.from === this.chatInfo.userId

            if (!isCurrentChat) {
                return
            }

            // 格式化消息对象
            const chatMessage = {
                id: message.id || Date.now(),
                type: message.messageType || 'text',
                content: message.content,
                time: new Date(message.timestamp || Date.now()),
                timestamp: message.timestamp || Date.now(),
                isSelf: message.isSelf,
                from: message.from,
                to: message.to,
                sender: message.sender,
                avatar: message.avatar,
                status: 'sent'
            }

            // 添加到消息列表
            this.messages.push(chatMessage)

            // 滚动到底部
            this.$nextTick(() => {
                this.scrollToBottom()
            })

            // 如果不是自己发送的消息，播放提示音
            if (!message.isSelf) {
                this.playMessageSound()
            }
        },

        // 播放消息提示音
        playMessageSound() {
            // 实现消息提示音播放
            const audio = new Audio('/message.mp3')
            audio.play().catch(err => console.error('播放提示音失败:', err))
        },

        // 更新消息日期
        updateMessageDates() {
            const dates = new Set()
            this.messages.forEach(message => {
                const date = new Date(message.time)
                const dateStr = this.formatDate(date)
                dates.add(dateStr)
            })
            this.messageDates = Array.from(dates)
        },

        // 格式化日期
        formatDate(date) {
            const today = new Date()
            const yesterday = new Date(today)
            yesterday.setDate(yesterday.getDate() - 1)

            if (date.toDateString() === today.toDateString()) {
                return '今天'
            } else if (date.toDateString() === yesterday.toDateString()) {
                return '昨天'
            } else {
                return `${date.getMonth() + 1}月${date.getDate()}日`
            }
        },

        // 格式化时间
        formatTime(timestamp) {
            const date = new Date(timestamp)
            const hours = date.getHours().toString().padStart(2, '0')
            const minutes = date.getMinutes().toString().padStart(2, '0')
            return `${hours}:${minutes}`
        },

        // 格式化消息内容（处理表情等）
        formatMessage(text) {
            // 简单的表情处理
            this.emojiList.forEach(emoji => {
                text = text.replace(new RegExp(emoji, 'g'), `<span class="emoji">${emoji}</span>`)
            })
            return text
        },

        // 判断是否显示消息时间
        showMessageTime(index) {
            if (index === 0) return true
            const currentMsg = this.messages[index]
            const prevMsg = this.messages[index - 1]
            return currentMsg.time - prevMsg.time > 5 * 60 * 1000 // 5分钟间隔显示时间
        },

        // 滚动到底部
        scrollToBottom() {
            if (this.$refs.messageList) {
                this.$nextTick(() => {
                    const messageList = this.$refs.messageList
                    messageList.scrollTop = messageList.scrollHeight
                })
            }
        },

        // 加载更多消息
        loadMoreMessages() {
            if (!this.isLoading && this.hasMoreMessages) {
                this.fetchMessages()
            }
        },

        // 发送文本消息
        sendTextMessage() {
            if (!this.inputMessage.trim()) {
                return
            }

            // 构建消息对象
            const message = {
                id: Date.now(),
                type: 'text',
                content: this.inputMessage,
                time: new Date(),
                timestamp: Date.now(),
                isSelf: true,
                from: this.currentUser.id,
                to: this.chatInfo.userId,
                sender: this.currentUser.nickname,
                avatar: this.currentUser.avatar,
                status: 'sending' // 发送状态：sending, sent, failed
            }

            // 添加到消息列表
            this.messages.push(message)

            // 清空输入框
            this.inputMessage = ''
            this.showEmojiPanel = false
            this.showMorePanel = false
            this.updateMessageDates()

            // 通过WebSocket发送消息
            const success = websocketApi.sendChatMessage(
                message.to,
                message.content,
                'text',
                {
                    sender: message.sender,
                    avatar: message.avatar
                }
            )

            // 更新消息状态
            if (success) {
                message.status = 'sent'
                // 将消息添加到Vuex存储
                this.$store.commit('addChatMessage', message)
            } else {
                message.status = 'failed'
                Toast('消息发送失败，请检查网络连接')
            }
        },

        // 切换语音输入
        toggleVoiceInput() {
            this.isVoiceInput = !this.isVoiceInput
            this.showEmojiPanel = false
            this.showMorePanel = false
        },

        // 开始录音
        startRecording() {
            this.$toast('开始录音...')
            // 实际项目中需要调用录音API
        },

        // 结束录音
        stopRecording() {
            this.$toast('录音结束')
            // 实际项目中需要处理录音文件并发送

            // 模拟发送语音消息
            const message = {
                id: Date.now(),
                type: 'voice',
                content: 'voice_message.mp3',
                duration: Math.floor(Math.random() * 30) + 1,
                time: Date.now(),
                isSelf: true,
                sender: '我',
                userId: 'self',
                avatar: 'https://i.pravatar.cc/100?img=10'
            }

            this.messages.push(message)
            this.updateMessageDates()
        },

        // 插入表情
        insertEmoji(emoji) {
            this.inputMessage += emoji
        },

        // 选择图片
        chooseImage() {
            this.$toast('选择图片功能开发中')
            this.showMorePanel = false

            // 模拟发送图片消息
            setTimeout(() => {
                const message = {
                    id: Date.now(),
                    type: 'image',
                    content: `https://picsum.photos/300/400?random=${Math.floor(Math.random() * 1000)}`,
                    time: Date.now(),
                    isSelf: true,
                    sender: '我',
                    userId: 'self',
                    avatar: 'https://i.pravatar.cc/100?img=10'
                }

                this.messages.push(message)
                this.updateMessageDates()
            }, 1000)
        },

        // 拍照
        takePhoto() {
            this.$toast('拍照功能开发中')
            this.showMorePanel = false
        },

        // 选择笔记
        chooseNote() {
            this.$toast('选择笔记功能开发中')
            this.showMorePanel = false

            // 模拟发送笔记消息
            setTimeout(() => {
                const message = {
                    id: Date.now(),
                    type: 'note',
                    content: '',
                    noteId: Math.floor(Math.random() * 1000),
                    thumbnail: `https://picsum.photos/300/400?random=${Math.floor(Math.random() * 1000)}`,
                    title: '我的旅行日记',
                    description: '记录美好的旅行时光...',
                    time: Date.now(),
                    isSelf: true,
                    sender: '我',
                    userId: 'self',
                    avatar: 'https://i.pravatar.cc/100?img=10'
                }

                this.messages.push(message)
                this.updateMessageDates()
            }, 1000)
        },

        // 分享位置
        shareLocation() {
            this.$toast('分享位置功能开发中')
            this.showMorePanel = false
        },

        // 预览图片
        previewImage() {
            this.$toast('图片预览功能开发中')
        },

        // 播放语音
        playVoice() {
            this.$toast('播放语音功能开发中')
        },

        // 播放视频
        playVideo() {
            this.$toast('播放视频功能开发中')
        },

        // 查看笔记
        viewNote(noteId) {
            if (noteId) {
                this.$router.push(`/detail/${noteId}`)
            }
        },

        // 查看用户资料
        viewUserProfile(userId) {
            if (userId === 'self') return
            this.$router.push(`/user/${userId}`)
        },

        // 显示聊天信息
        showChatInfo() {
            this.showGroupInfo = true
        },

        // 查看聊天详情
        viewChatDetail() {
            this.$router.push(`/chat-detail/${this.chatId}`)
        },

        // 返回
        onBack() {
            this.$router.back()
        }
    }
})
</script>

<style scoped>
.chat-container {
    display: flex;
    flex-direction: column;
    height: 100vh;
    background-color: #f1f1f1;
}

.chat-messages {
    flex: 1;
    overflow-y: auto;
    padding: 10px 15px;
}

.date-divider {
    text-align: center;
    margin: 10px 0;
}

.date-divider span {
    display: inline-block;
    padding: 3px 8px;
    background-color: rgba(0, 0, 0, 0.1);
    border-radius: 10px;
    font-size: 12px;
    color: #666;
}

.message-item {
    display: flex;
    margin-bottom: 15px;
}

.message-self {
    flex-direction: row-reverse;
}

.message-avatar {
    width: 40px;
    height: 40px;
    margin: 0 10px;
    flex-shrink: 0;
}

.message-avatar img {
    width: 100%;
    height: 100%;
    border-radius: 50%;
    object-fit: cover;
}

.message-content {
    max-width: 70%;
}

.message-sender {
    font-size: 12px;
    color: #999;
    margin-bottom: 2px;
}

.message-bubble {
    padding: 10px 12px;
    border-radius: 10px;
    background-color: #fff;
    word-break: break-word;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.self-bubble {
    background-color: #95ec69;
}

.message-time {
    font-size: 12px;
    color: #999;
    margin-top: 5px;
    text-align: center;
}

.message-image img {
    max-width: 200px;
    max-height: 200px;
    border-radius: 10px;
    object-fit: cover;
}

.message-voice {
    display: flex;
    align-items: center;
    padding: 10px 12px;
    border-radius: 10px;
    background-color: #fff;
    min-width: 80px;
}

.message-voice .van-icon {
    margin-right: 5px;
}

.message-video {
    width: 200px;
    border-radius: 10px;
    overflow: hidden;
}

.video-thumbnail {
    position: relative;
    width: 100%;
    height: 150px;
}

.video-thumbnail img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.play-icon {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    color: #fff;
    text-shadow: 0 1px 3px rgba(0, 0, 0, 0.3);
}

.message-note {
    width: 240px;
}

.note-card {
    display: flex;
    background-color: #fff;
    border-radius: 10px;
    overflow: hidden;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.note-image {
    width: 80px;
    height: 80px;
}

.note-image img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.note-info {
    flex: 1;
    padding: 8px;
    overflow: hidden;
}

.note-title {
    font-size: 14px;
    font-weight: 500;
    margin-bottom: 5px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.note-desc {
    font-size: 12px;
    color: #999;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
}

.load-more {
    text-align: center;
    padding: 10px 0;
    color: #999;
    font-size: 14px;
}

.chat-input-area {
    background-color: #f8f8f8;
    border-top: 1px solid #e5e5e5;
    padding: 10px;
}

.input-toolbar {
    display: flex;
    align-items: center;
    background-color: #fff;
    border-radius: 20px;
    padding: 5px 10px;
}

.input-toolbar .van-icon {
    margin: 0 5px;
    color: #666;
}

.input-toolbar .van-field {
    flex: 1;
    background-color: transparent;
}

.voice-button {
    flex: 1;
    text-align: center;
    background-color: #f1f1f1;
    border-radius: 20px;
    padding: 8px 0;
    color: #666;
    font-size: 14px;
}

.emoji-panel,
.more-panel {
    background-color: #fff;
    padding: 15px;
    height: 200px;
    overflow-y: auto;
}

.emoji-grid {
    display: grid;
    grid-template-columns: repeat(8, 1fr);
    gap: 10px;
}

.emoji-item {
    font-size: 24px;
    text-align: center;
    cursor: pointer;
}

.more-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 15px;
}

.more-item {
    display: flex;
    flex-direction: column;
    align-items: center;
}

.more-icon {
    width: 50px;
    height: 50px;
    background-color: #f1f1f1;
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 5px;
}

.more-text {
    font-size: 12px;
    color: #666;
}

.emoji {
    font-size: 18px;
    vertical-align: middle;
}

/* 群聊头像样式 */
.group-avatar {
    position: relative;
    width: 40px;
    height: 40px;
}

.group-avatar img {
    position: absolute;
    width: 30px;
    height: 30px;
    border-radius: 50%;
    border: 1px solid #fff;
    object-fit: cover;
}

.group-avatar img:nth-child(1) {
    top: 0;
    left: 0;
    z-index: 3;
}

.group-avatar img:nth-child(2) {
    top: 0;
    right: 0;
    z-index: 2;
}

.group-avatar img:nth-child(3) {
    bottom: 0;
    left: 50%;
    transform: translateX(-50%);
    z-index: 1;
}

/* 导航栏右侧操作按钮 */
.nav-right-actions {
    display: flex;
    align-items: center;
}

.nav-right-actions .van-icon {
    margin-left: 15px;
}
</style>